import React, { useState, useRef, useEffect } from 'react';
import { Toast, NavBar, Input, Cell, Button, Checkbox } from 'react-vant';
import { useNavigate } from 'react-router-dom';
import '../../../scss/fan/face.scss'
import axios from 'axios';
export default function face() {
    let navigate = useNavigate();
    useEffect(() => {
        startCamera();
    }, []);
    const videoRef = useRef(null);
    const canvasRef = useRef(null);
    const [capturedImages, setCapturedImages] = useState([]);
    const startCamera = async () => {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        videoRef.current.srcObject = stream;
    };

    const capture = () => {
        const canvas = canvasRef.current;
        const context = canvas.getContext('2d');
        context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
        const imageSrc = canvas.toDataURL('image/jpeg');

        setCapturedImages([...capturedImages, imageSrc])
        submitImages(imageSrc)
    };
    let submitImages = async (img) => {
        await axios.post('http://localhost:3000/users/faceLogin', { b64: img }).then(res => {
            console.log(res);
            if (res.data.code == 200) {
                localStorage.setItem('accessToken', JSON.stringify(res.data.accessToken))
                localStorage.setItem('user', JSON.stringify(res.data.data))
                Toast('登录成功')
                navigate('/waichu')
            } else {
                Toast(res.data.msg)
            }
        })
    };
  return (
    <div id='faceLogin'>
        <div id='faceLogin_video'>
                <video ref={videoRef} autoPlay />
            </div>
            <canvas ref={canvasRef} style={{ display: 'none' }} />
            <div id='button'>
                <Button type='primary' onClick={capture}>
                    登录
                </Button>
            </div>
    </div>
  )
}
